package com.hupu.jrs.components.jockeyjs

import android.webkit.WebView
import com.alibaba.fastjson.JSON

class DefaultJockeyImpl : JockeyImpl() {

    private var messageCount = 0

    override fun send(type: String, toWebView: WebView, withPayload: Any, complete: JockeyCallback) {
        var withPayload = withPayload
        val messageId = messageCount

        if (complete != null) {
            add(messageId, complete)
        }

        if (withPayload != null) {
            withPayload = JSON.toJSON(withPayload)
        }

        val url = String.format("javascript:Jockey.trigger(\"%s\", %d, %s)", type, messageId, withPayload)
        toWebView.loadUrl(url)

        ++messageCount
    }

    override fun triggerCallbackOnWebView(webView: WebView, messageId: Int) {
        val url = String.format("javascript:Jockey.triggerCallback(\"%d\")", messageId)
        webView.loadUrl(url)
    }
}
